package com.platform.modules.sys.service.impl;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.enumstatus.AptitudeEnum;
import com.platform.common.utils.Constant;
import com.platform.common.utils.HttpContextUtils;
import com.platform.common.utils.Query;
import com.platform.modules.mail.service.MailService;
import com.platform.modules.sys.dao.SysExamineStatusDao;
import com.platform.modules.sys.entity.SysExamineStatusEntity;
import com.platform.modules.sys.entity.SysOrgEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysExamineStatusService;
import com.platform.modules.sys.service.SysOrgService;
import com.platform.modules.sys.service.SysOrgUserService;
import com.platform.modules.sys.service.SysUserService;

/**
 * 数据字典Service实现类
 *
 * @author 肖亮
 */
@Service("sysExamineStatusService")
public class SysExamineStatusServiceImpl extends ServiceImpl<SysExamineStatusDao, SysExamineStatusEntity> implements SysExamineStatusService {

	@Autowired
	private MailService mailService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired	
	private SysOrgUserService sysOrgUserService;
	@Autowired	
	private SysOrgService sysOrgService;
	@Autowired	
	private SysExamineStatusService sysExamineStatusService;
	@Value("${spring.mail.emailTile}")
	private String emailTile;
	
	@Value("${spring.mail.orgPassemailTile}")
	private String orgPassemailTile;
	
	@Value("${spring.mail.orgNoPassemailTile}")
	private String orgNoPassemailTile;
	
	@Value("${spring.mail.emailParameter}")
	private String emailParameter;

	@Value("${spring.mail.tgEmailParameter}")
	private String tgEmailParameter;
	
	@Value("${spring.mail.btgEmailParameter}")
	private String btgEmailParameter;

	@Override
	public List<SysExamineStatusEntity> queryAll(Map<String, Object> params) {
		return baseMapper.queryAll(params);
	}

	@Override
	public IPage queryPage(Map<String, Object> params) {

		Page<SysExamineStatusEntity> page = new Query<SysExamineStatusEntity>(params).getPage();
		return page.setRecords(baseMapper.selectPage(page, params));
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public String auditOrg(String orgNo,String auditOrgNo,String auditor,String auditTxt,SysUserEntity  user,String orgStatus){
		
		String result = "SUCCESS";
		
		SysOrgEntity org = sysOrgService.getById(orgNo);
		if(org != null){
			if(StringUtils.isBlank(org.getOrgLinkMailbox())){
        		return "noEmail";
        	}
	    	SysExamineStatusEntity examineStatus = new SysExamineStatusEntity();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("auditId", orgNo);
//			params.put("auditOrgNo", auditOrgNo);
			params.put("auditType", AptitudeEnum.aptitudeType.ORG.getKey());
			List<SysExamineStatusEntity> list = sysExamineStatusService.queryAll(params);
			if(list != null && list.size()>0){
			    examineStatus.setId(list.get(0).getId());
			    examineStatus.setAuditTxt(auditTxt);
			    examineStatus.setAuditor(auditor);
			    examineStatus.setAuditOrgNo(auditOrgNo);
			    examineStatus.setAuditStatus(AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
				sysExamineStatusService.updateById(examineStatus);
			}else{
			    examineStatus.setAuditTxt(auditTxt);
			    examineStatus.setAuditor(auditor);
			    examineStatus.setAuditOrgNo(auditOrgNo);
		        examineStatus.setAuditTime(new Date());
		        examineStatus.setAuditId(orgNo);
		        examineStatus.setAuditType(AptitudeEnum.aptitudeType.ORG.getKey());
		        examineStatus.setAuditStatus(AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
			    sysExamineStatusService.save(examineStatus);
			}
		    //改变企业审核状态
			Date now = new Date();
			org.setStatus(orgStatus);
			org.setCheckOrg(auditOrgNo);
			org.setCheckTime(now);
			sysOrgService.updateById(org);
			
//			Map<String, Object> orgUserparams = new HashMap<String, Object>();
//			orgUserparams.put("orgNo", org.getOrgNo());
//			orgUserparams.put("accountType", "1");

//			List<SysOrgUserEntity> orgUserList = sysOrgUserService.queryAll(orgUserparams);
	        

			/**
			 * 	改变企业账号审核状态
			 * */
			//此时该orgNo的用户有且只有一个，所以可以直接使用getOne
			SysUserEntity sysUserEntity = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("ORG_NO", orgNo));
			if(sysUserEntity != null){
				sysUserEntity.setStatus(orgStatus);
				sysUserService.updateById(sysUserEntity);
				//获取后台服务器IP地址
				String localip = "localhost";
		        try {
			        localip=InetAddress.getLocalHost().getHostAddress();
			        System.out.println("获取IP地址"+localip);
				} catch (Exception e) {
					// TODO: handle exception
				}
		        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		        String dateString = formatter.format(new Date());
				 //发送邮箱
		        if("2".equals(orgStatus)){
		        	
		        	System.out.println(orgPassemailTile+"==================");
					String mailHtml=Constant.EMAIL_HTML_REG_SHTG;
					mailHtml=mailHtml.replaceAll("\\{emailTile\\}", orgPassemailTile);
					String webUrl=HttpContextUtils.getDomain();
					System.err.println(webUrl);
					mailHtml=mailHtml.replaceAll("\\{webUrl\\}", "http://"+localip+":70"); 
					mailHtml=mailHtml.replaceAll("\\{auditor\\}", user.getRealName());
					mailHtml=mailHtml.replaceAll("\\{auditTime\\}", dateString);
					mailHtml=mailHtml.replaceAll("\\{auditTxt\\}", auditTxt==null?"":auditTxt);
					mailHtml=mailHtml.replaceAll("\\{userName\\}", sysUserEntity.getUserName());
					mailHtml=mailHtml.replaceAll("\\{auditStatus\\}", "审核通过");
					mailHtml=mailHtml.replaceAll("\\{orgNo\\}", orgNo);
					System.err.println("tgEmailParameter==="+tgEmailParameter);
					mailHtml=mailHtml.replaceAll("\\{tgEmailParameter\\}", tgEmailParameter); 
					mailService.sendMail(org.getOrgLinkMailbox(), "验证邮件", mailHtml);
		        }else if("4".equals(orgStatus)){
		        	 //发送邮箱
					System.out.println(orgNoPassemailTile+"==================");
					String mailHtml=Constant.EMAIL_HTML_REG_SHBTG;
					mailHtml=mailHtml.replaceAll("\\{emailTile\\}", orgNoPassemailTile);
					String webUrl=HttpContextUtils.getDomain();
					System.err.println(webUrl);
					mailHtml=mailHtml.replaceAll("\\{webUrl\\}", "http://"+localip+":70"); 
					mailHtml=mailHtml.replaceAll("\\{auditor\\}", user.getRealName());
					mailHtml=mailHtml.replaceAll("\\{auditTime\\}", dateString);
					mailHtml=mailHtml.replaceAll("\\{auditTxt\\}", auditTxt == null?"":auditTxt);
					mailHtml=mailHtml.replaceAll("\\{auditStatus\\}", "审核未通过");
					mailHtml=mailHtml.replaceAll("\\{orgNo\\}", orgNo);
					System.err.println("btgEmailParameter==="+btgEmailParameter);
					mailHtml=mailHtml.replaceAll("\\{btgEmailParameter\\}", btgEmailParameter); 
					mailService.sendMail(org.getOrgLinkMailbox(), "验证邮件", mailHtml);
		        }
				
			}
			
		}else{
			return "noOrg";
		}

		return result;
	}
	
}
